<!-- 上门服务预约专家 -->
<template>
	<view>
		<uni-nav-bar title="预约专家" @clickLeft="goHome" left-icon="left" backgroundColor="#fff" color="#000"
			statusBar="true">
		</uni-nav-bar>
		<scroll-view class="scrollheight" scroll-y="true" :style="{height:setcollapseheight() + 'px'}">
			<u--form labelPosition="left" :model="model" :rules="rules" ref="form">
				<!-- 1.开始时间 -->
				<u-form-item label="开始时间" prop="formData.startDateTime" @click="showTimeDialog1">
					<view class="left-image">
						<image class="left-img" src="@/subPage1/static/service-order/calendar.png" mode="heightFix">
						</image>
					</view>
					<view style="pointer-events: none;">
						<u--input v-model="model.formData.startDateTime" readonly placeholder='请选择开始服务时间'
							border="none"></u--input>
					</view>
					<u-datetime-picker :show="showTimeStartFlag" :minDate="Number(new Date())" v-model="startTime" mode="datetime"
						@confirm="getShowStartTime" :formatter='formatter' @cancel="showTimeStartFlag=false">
					</u-datetime-picker>
				</u-form-item>
				<!-- 2.结束时间 -->
				<u-form-item label="结束时间" prop="formData.endDateTime" @click="showTimeDialog2">
					<view class="left-image">
						<image class="left-img" src="@/subPage1/static/service-order/calendar.png" mode="heightFix">
						</image>
					</view>
					<view style="pointer-events: none;">
						<u--input v-model="model.formData.endDateTime" placeholder='请选择结束服务时间' border="none"></u--input>
					</view>
					<u-datetime-picker :show="showTimeEndFlag" v-model="startTime" mode="datetime"
						@confirm="getShowEndTime" :formatter='formatter' @cancel="showTimeEndFlag=false">
					</u-datetime-picker>
				</u-form-item>
				<!-- 3.省市区 -->
				<u-form-item label="省市区" prop="formData.AllName">
					<view class="left-image">
						<image class="left-img" src="@/subPage1/static/service-order/jutidizhi.png" mode="heightFix"></image>
					</view>
					<picker mode="multiSelector" :range="array" range-key="name" :value="value" @columnchange="columnchange"
						@change="bindPickerChange">
						<span :style="{color:(AllName === '请选择 请选择 请选择' ? 'rgb(192, 196, 204)':'#000')}">{{AllName}}</span>
					</picker>
				</u-form-item>
				<!-- 4.具体地址 -->
				<u-form-item label="具体地址" prop="formData.address">
					<view class="left-image">
						<image class="left-img" src="@/static/index-message/jigou.png" mode="heightFix"></image>
					</view>
					<u--input v-model="model.formData.address" placeholder='请输入具体地址' border="none"></u--input>
				</u-form-item>
				<!-- 5.联系人 -->
				<u-form-item label="联系人" prop="formData.contact">
					<view class="left-image">
						<image class="left-img" src="@/subPage1/static/machinery/xingming.png" mode="heightFix"></image>
					</view>
					<u--input v-model="model.formData.contact" placeholder='请输入联系人' border="none"></u--input>
				</u-form-item>
				<!-- 6.联系方式 -->
				<u-form-item label="联系方式" prop="formData.contactMethod">
					<view class="left-image">
						<image class="left-img" src="@/subPage1/static/machinery/lianxidianhua.png"mode="heightFix"></image>
					</view>
					<u--input v-model="model.formData.contactMethod" placeholder='请输入联系方式' type="number"
						border="none"></u--input>
				</u-form-item>
				<!-- 7.内容 -->
				<u-form-item class="textContent" prop="formData.content" style="position: static;width: 100%;">
					<view class="content">
						<uni-easyinput type="textarea" v-model="model.formData.content" @input="easyInputChange" placeholder="请简要描述需咨询的内容"
							style="background-color: #fff;box-shadow: 0rpx 0rpx 12rpx 2rpx rgba(0, 0, 0, 0.05);border-radius: 16rpx;"></uni-easyinput>
					</view>
				</u-form-item>
				<u-form-item  label="上传照片">
					<view class="left-image">
						<image class="left-img" src="@/subPage1/static/machinery/tuwenxiangqing.png" mode="heightFix"></image>
					</view>
					<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="1" multiple
						deletable :maxCount="3">点击上传</u-upload>
				</u-form-item>
				<u-form-item  label="上传视频">
					<view class="left-image">
						<image class="left-img" src="@/subPage1/static/machinery/tuwenxiangqing.png" mode="heightFix"></image>
					</view>
					<u-upload :fileList="fileList2" @afterRead="afterVideoRead" @delete="deleteVed" name="2" multiple :maxCount="1"
						accept="video">点击上传</u-upload>
				</u-form-item>
			</u--form>
		</scroll-view>
		<!-- 提交 -->
		<view class="submit">
			<button @click="recordaddmet()" class="submit-btn">
				<text>提交预约</text>
			</button>
		</view>
	</view>
</template>

<script>
	import serviceApi from '@/api/socialized-servce/specialist-consultation/order/index.js'
	import { addressList }from '@/subPage1/plugins/address.js'
	import {
		baseurl,
		cloudBaseurl,
		agrServiceUrl
	} from '@/config/baseUrl.js'
	export default {
		data() {
			return {
				startTime: Number(new Date()),
				model: {
					formData: {
						AllName: '',
						serviceProviderNo: uni.getStorageSync('serviceProviderNo'),
						startDateTime: null,
						endDateTime: null,
						provinceId: '',
						cityId: '',
						areaId: '',
						address: '',
						contact: '',
						contactMethod: '',
						content: '',
						imgList: [],
						videoList: []
					}
				},
				rules: {
					'formData.startDateTime': [{
							type: 'string',
							required: true,
							message: '开始时间不能为空',
							trigger: ['blur', 'change']
						},
						{
							type: 'string',
							validator: (rule, value, callback) => {
								if (this.model.formData.endDateTime) {
									if (new Date(value).getTime() < new Date(this.model.formData.endDateTime)
										.getTime()) {
										return true
									} else {
										return false
									}
								} else {
									return true
								}
							},
							message: '开始时间不能大于等于结束时间',
							trigger: ['blur', 'change']
						}
					],
					'formData.endDateTime': [{
							type: 'string',
							required: true,
							message: '结束时间不能为空',
							trigger: ['blur', 'change']
						},
						{
							type: 'string',
							validator: (rule, value, callback) => {
								if (this.model.formData.startDateTime) {
									if (new Date(value).getTime() > new Date(this.model.formData.startDateTime)
										.getTime()) {
										return true
									} else {
										return false
									}
								} else {
									return true
								}
							},
							message: '结束时间不能小于等于开始时间',
							trigger: ['blur', 'change']
						}
					],
					'formData.AllName': {
						type: 'string',
						required: true,
						message: '请选择省市区',
						trigger: ['blur', 'change']
					},
					'formData.address': {
						type: 'string',
						required: true,
						message: '具体地址不能为空',
						trigger: ['blur', 'change']
					},
					'formData.contact': {
						type: 'string',
						required: true,
						message: '联系人不能为空',
						trigger: ['blur', 'change']
					},
					'formData.contactMethod': [{
							type: 'string',
							required: true,
							message: '联系方式不能为空',
							trigger: ['blur', 'change']
						},
						{
							type: 'string',
							validator: (rule, value, callback) => {
								if (value.length <= 11) {
									if (value != '') {
										return this.$u.test.mobile(value)
									}
								} else {
									return false
								}
							},
							message: '手机号格式不对,请输入正确的手机号',
							trigger: ['blur', 'change']
						}
					],
					'formData.content': {
						type: 'string',
						required: true,
						message: '内容不能为空',
						trigger: ['blur', 'change']
					},
				},
				status: 1,
				startDateTime: '',
				endDateTime: '',
				showTimeStartFlag: false, //时间
				showTimeEndFlag: false,
				array: [],
				value: [0, 0, 0],
				index: 0,
				AllName: '',
				AllAddress: addressList,
				selectVal: ['', '', ''],
				// 图片or视频相关
				fileList: [],
				pictureIdList: [],
				fileList2: [],
				collectData: {
					invitationTypeId: 0,
					invitationTitle: '',
					invitationContent: '',
					imgList: [],
					vedioList: []
				},
				type: '',
				arr: []
			}
		},
		onLoad(e) {
			this.status = e.status
			this.model.formData.personId = e.id
		},
		created() {
			let userInfo = JSON.parse(uni.getStorageSync('userServerInfo'))
			this.model.formData.contact = userInfo.userName
			this.model.formData.contactMethod = userInfo.phoneNumber
			this.initSelect()
		},
		methods: {
			// 开始时间
			showTimeDialog1() {
				this.showTimeStartFlag = true
			},
			// 结束时间
			showTimeDialog2() {
				this.showTimeEndFlag = true
			},
			getShowStartTime(e) {
				this.model.formData.startDateTime = this.getTime(e.value)
				this.showTimeStartFlag = false
				this.$refs.form.validateField('formData.startDateTime')
			},
			getShowEndTime(e) {
				console.log(e.value);
				this.model.formData.endDateTime = this.getTime(e.value)
				// console.log(this.model.formData.endTime);
				this.showTimeEndFlag = false
				this.$refs.form.validateField('formData.endDateTime')
			},
			// 
			showTimeDialog1() {
				this.showTimeStartFlag = true
			},
			showTimeDialog2() {
				this.showTimeEndFlag = true
			},
			// 迭代
			hourFilter(e, arr) {
				if (e === 'hour') {
					let arr2 = []
					let arr1 = ['00', '06', '23']
					arr1.forEach(el => {
						if (arr.findIndex(ell => el === ell) === -1) return
						arr.splice(arr.findIndex(ell => el === ell), 1)
					})
					return arr.map(it => it)
				} else {
					return arr.map(el => el)
				}
			},
			formatter(type, value) {
				if (type === 'year') {
					return value + '年'
				} else if (type === 'month') {
					return value + '月'
				} else if (type === 'day') {
					return value + '日'
				} else if (type === 'hour') {
					return value + '时'
				} else if (type === 'minute') {
					return value + '分'
				} else if (type === 'second') {
					return value + '秒'
				}
				return value
			},
			// 时间戳计算
			getTime(timestamp) {
				// 时间戳转化
				let date = new Date()
				if (timestamp) date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000

				const Y = date.getFullYear() + '-';
				const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
				const D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';

				const h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':';
				const m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) + ':';
				const s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
				return Y + M + D + h + m + s;
			},
			// 开始时间
			getShowTime1(e) {
				this.startDateTime = this.getTime(e.value)
				this.showTimeStartFlag = false
			},
			// 结束时间
			getShowTime2(e) {
				// this.formData.endDateTime = e.value
				this.endDateTime = this.getTime(e.value)
				this.showTimeEndFlag = false
			},
			// 省市区
			bindPickerChange(e) {
				this.model.formData.provinceId = this.value[0]
				this.model.formData.cityId = this.value[1]
				this.model.formData.areaId = this.value[2]
			},
			columnchange(d) {
				this.updateSelectIndex(d.detail.column, d.detail.value) // 更新选择索引
					.updateSourceDate() // 更新源数据
					.updateAddressDate() // 更新结果数据
			},
			initSelect() {
				this.updateSourceDate() // 更新源数据
				this.updateAddressDate() // 更新结果数据
			},
			updateSourceDate() {
				this.array = []
				this.array[0] = this.AllAddress.map(obj => {
					return {
						name: obj.name
					}
				})
				this.array[1] = this.AllAddress[this.value[0]].city.map(obj => {
					return {
						name: obj.name
					}
				})
				this.array[2] = this.AllAddress[this.value[0]].city[this.value[1]].area.map(obj => {
					return {
						name: obj.name
					}
				})
				return this
			},
			updateSelectIndex(column, value) {
				let arr = JSON.parse(JSON.stringify(this.value))
				arr[column] = value
				if (column === 0) {
					arr[1] = 0
					arr[2] = 0
				}
				if (column === 1) {
					arr[2] = 0
				}
				this.value = arr
				return this
			},
			updateAddressDate() {
				this.selectVal[0] = this.array[0][this.value[0]].name
				this.selectVal[1] = this.array[1][this.value[1]].name
				this.selectVal[2] = this.array[2][this.value[2]].name
				this.AllName = `${this.selectVal[0]} ${this.selectVal[1]} ${this.selectVal[2]}`
				if(this.AllName !== '请选择 请选择 请选择') {
					this.model.formData.AllName = this.AllName
					this.$refs.form.validateField('formData.AllName')
				}
			},
			easyInputChange() {
				this.$refs.form.validateField('formData.content')
			},
			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1)
				this.collectData.imgList.splice(event.index, 1)		
			},
			// 删除视频
			deleteVed(event) {
				this.fileList2.splice(event.index, 1)
				this.collectData.vedioList.splice(event.index, 1)
				console.log(this.collectData.vedioList);
			},
			// 添加图片
			async afterRead(event) {
				this.type = 'image'
				console.log(event);
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.fileList.length
				lists.map((item) => {
					this.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.fileList[fileListLen]
					this.fileList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
				this.afterfileList = this.fileList

			},
			// 上传视频
			async afterVideoRead(event) {
				this.type = 'video'
				this.duration = event.file[0].duration

				console.log(event.file[0].duration, '视频');
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.fileList2.length
				lists.map((item) => {
					this.fileList2.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.fileList2[fileListLen]
					this.fileList2.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
				this.afterfileList = this.fileList2
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: agrServiceUrl + `common/file/upDown/getUploadUrl?moduleType=XG_ORGANIZATION&upDownType=FTP`,
						filePath: url,
						name: 'file',
						header: {
							// "moduleType": 'EXPERT',
							'token': uni.getStorageSync("satoken") || ''
						},
						formData: {},
						success: async (res) => {
							const dataObj = JSON.parse(res.data);
							const data = dataObj.data;
							console.log(data, 'ww');
							resolve(data);
							if (this.type == 'image') {
								this.collectData.imgList.push({
									// invitationImgUrl: `${agrServiceUrl}` + data.slice(1),
									imgId: data.slice(33)
								})
							} else {
								this.collectData.vedioList.push({
									// invitationVedioUrl: `${agrServiceUrl}` + data.slice(1),
									// vedioImgUrl: '',
									videoId: data.slice(38),
									// duration: this.duration
								})
							}
							console.log(this.collectData, this.type);
							if (this.pictureIdList.includes(data)) return
							else {
								setTimeout(() => {
									this.pictureIdList.push(data)
								}, 1000)

							}
						},
						fail: () => {
							uni.showToast({
								title: '图片上传失败',
								icon: 'error'
							})
						}
					});
				})
			},
			// 提交预约
			async recordaddmet() {
				this.$refs.form.validate().then(async () => {
					this.model.formData.imgList = []
					this.model.formData.videoList = []
					this.model.formData.imgList = this.collectData.imgList
					this.model.formData.videoList = this.collectData.vedioList
					let params = {
						...this.model.formData
					}
					delete params.AllName
					params.startDateTime = new Date(this.model.formData.startDateTime).getTime()
					params.endDateTime = new Date(this.model.formData.endDateTime).getTime()
					// console.log(params); return
					let res = await serviceApi.submitAppointment(params)
					if(res.code === 200) {
						uni.showToast({
							title: '预约成功',
							icon: 'success'
						})
						uni.redirectTo({
							url: '/subPage1/socialized-service/specialist-consultation/user-module/door-service/my-order/my-order'
						})
					} else {
						uni.showToast({
							title: res.msg,
							icon: "error"
						})
					}
				}).catch(errors => {
					console.log("失败信息:" + JSON.stringify(errors))
				})
			},
			goHome() {
				uni.redirectTo({
					url: '/subPage1/socialized-service/specialist-consultation/user-module/expert-information/expert-information'
				})
			},
			setcollapseheight() {
				let topheightone = uni.upx2px(136)
				let winHeight = 0
				uni.getSystemInfo({
					success: function(res) {
						winHeight = res.windowHeight
					}
				});
				let bottomHeight = uni.upx2px(180)
				winHeight = parseInt(winHeight) - topheightone - bottomHeight
				// #ifndef H5
				winHeight = winHeight
			
				// #endif
				return winHeight
			},
		}
	}
</script>

<style lang="scss" scoped>
	/deep/.u-form {
		padding: 0 32rpx;
		.u-form-item {
			position: relative;
			background-color: #fff;
			margin-top: 20rpx;
			border-radius: 20rpx;
			&:nth-child(n+8) {
				background-color: #E2E7F8;
			}
		}
		
		.content {
			margin-top: 20rpx;
		}
		// 左侧img
		.left-image {
			position: absolute;
			left: 0;
			width: 54rpx;
			height: 54rpx;
			border-radius: 50%;
			margin-left: 22rpx;
			display: flex;
			justify-content: center;
			align-content: center;
			flex-wrap: wrap;
			
			.left-img {
				height: 26rpx;
			}
		}
		
		.u-form-item__body__left {
			width: 200rpx !important;
			margin-left: 50px;
		}
		
		// 右侧icon
		.u-icon--right {
			position: absolute;
			right: 0;
			top: 50%;
			transform: translateY(-50%);
		}
		// 上传图片
		.u-upload__deletable__icon {//删除icon
			top: 12rpx;
			right: 2rpx;
			transform: scale(1.7);
		}
		
		.uploadBtns {//身份证
			display: flex;
		}
		.u-upload__wrap {
			display: flex!important;
			align-items: center;
		}
		.u-upload__wrap__preview__other {
			height: 80rpx !important;
			width: 80rpx !important;
		}
		
		.textContent {
			margin-top: 0;
			background-color: transparent;
			
			.u-form-item__body {
				padding: 0;
				
				.u-form-item__body__right__content__slot {
					width: 100%!important;
					.content {
						width: 100%;
					}
				}
			}
		}
	}
	
	.submit {
		position: fixed;
		bottom: 60rpx;
		left: 50%;
		transform: translateX(-50%);
	
		.submit-btn {
			width: 340rpx;
			height: 60rpx;
			line-height: 60rpx;
			background: linear-gradient(270deg, #88ACFF 0%, #2165FF 100%);
			border-radius: 56rpx 56rpx 56rpx 56rpx;
			font-size: 28rpx;
			color: #FFFFFF;
			display: flex;
			justify-content: center;
			align-items: center;
	
			.icon-submit {
				margin-right: 10rpx;
			}
		}
	}

	
	.uni-input-input {
		pointer-events: none;
	}
	
	/deep/ .uni-scroll-view {
		position: relative;
		.uni-scroll-view-content {
			position: absolute;
			top: 0;
		}
	}
</style>